/**
 * https://leetcode.cn/submissions/detail/577017555/
 * 233. 数字 1 的个数
 * Hard, 黄伟杰 2024.10.30
 * 数位DP
 */
#include <bits/stdc++.h>
using namespace std;

class Solution
{
public:
    int countDigitOne(int n)
    {
        string s = to_string(n);
        int m = s.length();
        vector<vector<int>> memo(m, vector<int>(m, -1));
        auto dfs = [&](auto &&dfs, int i, int cnt, bool is_limit) -> int
        {
            if (i == m)
            {
                return cnt;
            }
            if (!is_limit && memo[i][cnt] != -1)
            {
                return memo[i][cnt];
            }
            int res = 0;
            int up = is_limit ? s[i] - '0' : 9;
            for (int d = 0; d <= up; d++)
            {
                res += dfs(dfs, i + 1, cnt + (d == 1), is_limit && d == up);
            }
            if (!is_limit)
            {
                memo[i][cnt] = res;
            }
            return res;
        };
        return dfs(dfs, 0, 0, true);
    }
};